package com.hqbzl.c1.executors;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
public class TestExecutor {
    public static void main(String[] args) {
//        new ThreadPoolExecutor()
//        f1();
//        f2();
        f4();
    }

    private static void f1() {
        final ExecutorService threadPool = Executors.newFixedThreadPool(2);
        threadPool.execute(() -> {
            log.debug("{}", 1);
        });
        threadPool.execute(() -> {
            log.debug("{}", 2);
        });
        threadPool.execute(() -> {
            log.debug("{}", 3);
        });
    }

    private static void f2() {
        final ExecutorService threadPool1 = Executors.newFixedThreadPool(2, new ThreadFactory() {
            private AtomicInteger id = new AtomicInteger(1);

            @Override
            public Thread newThread(Runnable r) {
                final Thread thread = new Thread(r, "cc-" + id.getAndIncrement());
                if (thread.isDaemon()) {
                    thread.setDaemon(false);
                }
                return thread;
            }
        });
        threadPool1.execute(() -> {
            log.debug("{}", 1);
        });
        threadPool1.execute(() -> {
            log.debug("{}", 2);
        });
        threadPool1.execute(() -> {
            log.debug("{}", 3);
        });
    }

    private static void f3() {
        final ExecutorService pool = Executors.newCachedThreadPool();
        pool.execute(() -> {
            log.debug("r1");
        });
    }

    private static void f4() {
        final ExecutorService pool = Executors.newSingleThreadExecutor();
        pool.execute(() -> {
            log.debug("threaa 1");
            log.debug("{}", 1 / 0);
        });
        pool.execute(() -> {
            log.debug("{}", 1);
        });
        pool.shutdown();
        try {
            pool.awaitTermination(3, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private static void f5() {
        final ScheduledExecutorService pool = Executors.newScheduledThreadPool(1);
        pool.scheduleAtFixedRate(() -> {
            System.out.println("running = >");
        }, 1, 1000, TimeUnit.SECONDS);


    }

}
